// pages/login/index.js
const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    userInfo: {},
    winWidth: 0,
    winHeight: 0,
    loginInput: false,
    isLogin: false,
    isSaveLogin: false,
    canIUseGetUserProfile: false,
    username: '',
    password: '',
  },
  onLoad: function (options) {
    // 生命周期函数--监听页面加载
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    if (wx.canIUse('getUserProfile')) {
      that.setData({
        canIUseGetUserProfile: true
      })
    }

    // that.setData({
    //   isLogin: true
    // });

    // 获取用户信息
    http.ApiGet(apiUrl.UrlUserInfo, {}, function (res) {
      console.log(res);
      if (res.result.errorCode == 1) {
        that.setData({
          isLogin: false
        });
        var user = res.user;
        wx.setStorageSync("user", user)
        that.switchTab();
      } else {
        var username = wx.getStorageSync("username");
        var password = wx.getStorageSync("password");
        var isSaveLogin = true;
        if (!username) {
          username = '';
          isSaveLogin = false;
        }
        if (!password) {
          password = '';
        }
        that.setData({
          isLogin: true,
          username: username,
          password: password,
          isSaveLogin: isSaveLogin
        });
      }
    });
  },
  switchTab: function () {
    this.doCheck();
    wx.reLaunch({
      url: '../service/index'
    });
  },
  formSubmit: function (e) {

    var that = this;

    var formData = e.detail.value;

    console.log(formData);

    if (formData.username == "") {
      wx.showModal({
        title: '请填写用户名/手机号',
      });
      return;
    }

    if (formData.password == "") {
      wx.showModal({
        title: '请填写密码',
      });
      return;
    }

    wx.showToast({
      title: '正在提交',
      icon: 'loading',
      duration: 2000,
      mask: true,
    });

    http.ApiPost(apiUrl.UrlLogin, formData, function (res) {

      if (res.result.errorCode == 1) {
        var user = res.userinfo;

        wx.showToast({
          title: '登录成功！',
          icon: 'success',
          duration: 5000
        })

        var isSaveLogin = that.data.isSaveLogin;
        if (isSaveLogin) {
          wx.setStorageSync("username", formData.username);
          wx.setStorageSync("password", formData.password);
        } else {
          wx.setStorageSync("username", "");
          wx.setStorageSync("password", "");
        }
        wx.setStorageSync("user", user);
        var token = user.token;
        wx.setStorageSync("token", token);

        that.switchTab();

      } else {
        wx.showModal({
          title: res.result.errorMessage
        });
      }
    });
  },
  radioTap: function () {
    var isSaveLogin = this.data.isSaveLogin;
    if (isSaveLogin) {
      this.setData({
        isSaveLogin: false,
      });
    } else {
      this.setData({
        isSaveLogin: true,
      });
    }
  },
  loginInputTap: function () {
    this.setData({
      loginInput: !this.data.loginInput,
    });
  },
  protocolTap: function () {
    wx.navigateTo({
      url: '../protocol/index'
    });
    // wx.setClipboardData({
    //   data: "https://www.sogx.cn/",
    //   success: function (res) {
    //     console.log(res);
    //   }
    // });
  },
  doCheck: function () {


    var user = wx.getStorageSync("user");
    var uid = 0;
    if (user) {
      uid = user.id;
    }

    //获取用户信息
    http.ApiGet(apiUrl.UrlCheck, {"uid":uid}, function (res) {
      console.log(res);
      if (res.code == 1) {
        wx.setStorageSync("isCheck", true);
      } else {
        wx.setStorageSync("isCheck", false);
      }
    });
  },
  authLogin: function (e) {
    console.log(e.detail.userInfo)
    if (e.detail.userInfo) {
      this.getUserInfo();
    }
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    var that = this;
    wx.getUserProfile({
      desc: '用于完善用户资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        var userInfo = res.userInfo;
        console.log('userInfo', userInfo);
        
        //更新数据
        that.setData({
          userInfo: userInfo
        })
        wx.setStorageSync("wx_userInfo", userInfo);

        var openId = wx.getStorageSync("openId");
        if (!openId) { //检查本地的openId
          wx.cloud.callFunction({
            name: 'getOpenData',
            complete: res => {
              var openId = res.result.userInfo.openId;
              console.log('callFunction result: ', res.result);
              wx.setStorageSync("openId", openId);
              that.doLogin(openId);
            }
          })
        } else {
          that.doLogin(openId);
        }
      }
    })
  },
  getUserInfo: function () {
    var that = this;
    //调用登录接口
    wx.getUserInfo({
      withCredentials: false,
      success: function (res) {
        var userInfo = res.userInfo;
        console.log('userInfo', userInfo);

        //更新数据
        that.setData({
          userInfo: userInfo
        })
        wx.setStorageSync("wx_userInfo", userInfo);

        var openId = wx.getStorageSync("openId");
        if (!openId) { //检查本地的openId
          wx.cloud.callFunction({
            name: 'getOpenData',
            complete: res => {
              var openId = res.result.userInfo.openId;
              console.log('callFunction result: ', res.result);
              wx.setStorageSync("openId", openId);
              that.doLogin(openId);
            }
          })
        } else {
          that.doLogin(openId);
        }
      }
    })
  },
  doLogin: function (openId) {
    var that = this;
    //先登录试试
    http.ApiPost(apiUrl.UrlLogin, {"openid":openId}, function (res) {

      if (res.result.errorCode == 1) {
        var user = res.userinfo;

        wx.showToast({
          title: '登录成功！',
          icon: 'success',
          duration: 5000
        })

        wx.setStorageSync("user", user);
        var token = user.token;
        wx.setStorageSync("token", token);

        that.switchTab();
        // that.doRegister();

      } else {
        //注册
        that.doRegister();
      }
    });
  },
  doRegister: function () {
    wx.navigateTo({
      url: '../register/index'
    });
  },
  onShareAppMessage: function () {
    // 用户点击右上角分享
    return {
      title: '同心云会员系统', // 分享标题
      desc: '', // 分享描述
      path: '/pages/login/index' // 分享路径
    }
  },
  onShareTimeline: function() {
    return {
      title: "同心云会员系统", // 分享标题
      query: '', // 分享路径参数
      imageUrl: 'http://s.sogx.cn/uploadfile/45/20200927/549c914401ffe7c7ebb521ee3b20f92a.png'
    }
  },
})